package com.zds.support.api.retrofit.interceptor

import android.content.pm.PackageManager
import android.text.TextUtils
import com.zds.support.manager.UserDataManager
import com.zds.support.util.AppUtils
import okhttp3.Interceptor
import okhttp3.Response
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern


class ApiInterceptor : Interceptor {
    private val TAG = "ApiInterceptor"
    private var versionCode: String = "${AppUtils.getVersionCode()}"
    private var versionName: String = ""
    private var deviceInfo: String = "${android.os.Build.BRAND} ${android.os.Build.MODEL} ${android.os.Build.VERSION.RELEASE}"
    private var deviceId: String = AppUtils.getDeviceId()
    private val gmtDateFormat = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US)
    private var userAgent: String = ""
    private var isAndroidPad: Boolean = false
    private var isCheckServerTime = false

    constructor(isPad:Boolean) {
        isAndroidPad = isPad
        try {
            versionName = AppUtils.getVersionName();
        } catch (e: PackageManager.NameNotFoundException) {

        }
        try {
            userAgent = AppUtils.getUserAgent()
        } catch (e: Exception) {
            userAgent = ""
        }

        val packageName = AppUtils.appContext.packageName
        val reg = "[\u4e00-\u9fa5]"
        val pat = Pattern.compile(reg)
        val mat = pat.matcher(deviceInfo)
        deviceInfo = mat.replaceAll("*")
        gmtDateFormat.timeZone = TimeZone.getTimeZone("GMT")
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val token = UserDataManager.instance.getToken()
        var channel = "global"
        val newBuilder = request.newBuilder()
                .addHeader("token", token)
                .addHeader("version", versionName)
                .addHeader("version_code", versionCode)
                .addHeader("device_info", deviceInfo)
                .addHeader("deviceId", deviceId)
                .addHeader("time_millis", System.currentTimeMillis().toString())
                .addHeader("timeZone", Locale.getDefault().toString())
                .addHeader("TIME-ZONE", TimeZone.getDefault().id)
                .addHeader("channel", channel)
        if (!TextUtils.isEmpty(userAgent)) {
            newBuilder.removeHeader("User-Agent")
                    .addHeader("User-Agent", userAgent)
        }
        val response = chain.proceed(newBuilder.build())

        return response
    }


}